// src\composables\useRSAEncrypt.js
import { JSEncrypt } from 'jsencrypt';
import LoginAPI from '@/api/admin/login';

export function useRSAEncrypt() {
  // 响应式状态
  const publicKey = ref(null);
  const isLoading = ref(false);

  // 动态获取公钥
  const fetchPublicKey = async () => {
    try {
      isLoading.value = true;
      const { data } = await LoginAPI.getPublicKey();
      publicKey.value = data;
    } catch (err) {
      console.error(err);
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  // 加密方法
  const encrypt = async (plainText) => {
    try {
      // 确保公钥已加载
      if (!publicKey.value) {
        console.log('从服务器加载公钥......');
        await fetchPublicKey();
      } else {
        console.log('使用公钥缓存......');
      }
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey(publicKey.value);

      const encrypted = encryptor.encrypt(plainText);
      if (!encrypted) {
        throw new Error('加密失败，请检查公钥有效性');
      }

      return encrypted;
    } catch (err) {
      console.error(err);
      throw err;
    }
  };

  return {
    // 暴露状态和方法
    isLoading,
    encrypt,
  };
}
